package com.cat.yygh.user.controller.user;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cat.yygh.common.exception.YyghException;
import com.cat.yygh.common.result.R;
import com.cat.yygh.common.util.JwtHelper;
import com.cat.yygh.model.user.UserInfo;
import com.cat.yygh.user.prop.WeixinProperties;
import com.cat.yygh.user.service.UserInfoService;
import com.cat.yygh.user.utils.HttpClientUtils;
import com.sun.deploy.net.URLEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user/userinfo/wx")
public class WeixinController {
    @Autowired
    private WeixinProperties weixinProperties;
    @Autowired
    private UserInfoService userInfoService;
    @RequestMapping("/param")
    @ResponseBody
    private R WeixinLoginParam() throws UnsupportedEncodingException {
        String url = URLEncoder.encode(weixinProperties.getRedirecturl(),"UTF-8");//用户处理回调
        Map<String, Object> map = new HashMap<>();
        map.put("appid",weixinProperties.getAppid());
        map.put("scope","snsapi_login");
        map.put("redirecturl",url);
        map.put("state",System.currentTimeMillis()+"");
        return R.ok().data(map);
    }
    @GetMapping("/callback")
    //固定的格式 code state 微信二维码回调地址
    private String callback(String code,String state) throws Exception {
        StringBuilder builder = new StringBuilder();
        StringBuilder append = builder.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String format = String.format(append.toString(), weixinProperties.getAppid(), weixinProperties.getAppsecret(), code);
        String result = HttpClientUtils.get(format);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");


        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        if (userInfo == null){
            //给微信服务器发送请求获取用户信息
            StringBuilder sb = new StringBuilder();
            StringBuilder appends = sb.append("https://api.weixin.qq.com/sns/userinfo")
                    .append("?access_token=%s")
                    .append("&openid=%s");
            String formats = String.format(appends.toString(), access_token, openid);
            String results = HttpClientUtils.get(formats);
            JSONObject parseObject = JSONObject.parseObject(results);
            String nickname = parseObject.getString("nickname");
            //首次登录 保存信息入库
            userInfo = new UserInfo();
            userInfo.setOpenid(openid);
            userInfo.setNickName(nickname);
            userInfo.setStatus(1);
            userInfoService.save(userInfo);
         }
        //5. 验证用户状态status
        Map<String, String> map = new HashMap<String,String>();
        if (userInfo.getStatus() == 0){
            throw new YyghException(20001,"用户锁定中");
        }
        if (StringUtils.isEmpty(userInfo.getPhone())){
            //手机号为空首次登录s
            map.put("openid",openid);
        }else {
            //手机号不是为空的不是首次登录
            map.put("openid","");
        }
        //6. 返回用户信息
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }

        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("name",name);
        map.put("token",token);
        //重定向到某一个页面
        return "redirect:http://localhost:3000/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+URLEncoder.encode(map.get("name"),"utf-8");
    }
}
